#pragma once

#include "CentralCache.h"
#include "Common.h"

class ThreadCache {
  public:
    // 线程申请 size 大小空间
    void *Allocate(size_t size) {
        assert(size <= MAX_BYTES);

        size_t alignSize = SizeClass::RoundUp(size);
        size_t index = SizeClass::Index(alignSize);

        if (!_freeLists[index].Empty()) {
            return _freeLists[index].Pop();
        } else {
            return FetchFromCentralCache(index, alignSize);
        }
    }

    // 回收线程中大小为 size 的 obj 空间
    void Deallocate(void *obj, size_t size) {
        assert(obj);
        assert(size <= MAX_BYTES);

        size_t index = SizeClass::Index(size);
        _freeLists[index].Push(obj);
    }

    void *FetchFromCentralCache(size_t index, size_t alignSize) {
        size_t batchNum = std::min(_freeLists[index].MaxSize(), SizeClass::NumMoveSize(alignSize));
        if (batchNum == _freeLists[index].MaxSize()) {
            _freeLists[index].MaxSize()++;
        }

        void *start = nullptr;
        void *end = nullptr;
        size_t actulNum = CentralCache::GetInstance()->FetchRangeObj(start, end, batchNum, alignSize);

        return nullptr;
    }

  private:
    FreeList _freeLists[FREE_LIST_NUM];
};

static thread_local ThreadCache *pTLSThreadCache = nullptr;  // thread_local是C++11提供的，能跨平台
